#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @File    : emaildriver
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2023/10/28 22:41
# @Describe: 
# ==================================================
import os
import smtplib
from email.mime.text import MIMEText
from library.tools.file_tool.setting import root_path
from library.tools.file_tool.operationFileControl import read_yaml_to_dict
from library.log.log_control import INFO, ERROR


class SendEmail:
    """ 发送邮箱 """

    def __init__(self):
        self.config = read_yaml_to_dict(os.path.join(root_path(), "config/notifyconfig.yaml"))

    def send_email(self, content: str) -> None:
        """
        @param content: 发送内容
        @return:
        """
        user_list = self.config['email']['send_list'].split(',')
        user = f"liuxiangui<{self.config['email']['send_user']}>"
        message = MIMEText(content, _subtype='plain', _charset='utf-8')
        message['Subject'] = self.config['project_name']
        message['From'] = user
        message['To'] = ";".join(user_list)
        server = smtplib.SMTP()
        try:
            server.connect(self.config['email']['email_host'])
            server.login(self.config['email']['send_user'], self.config['email']['stamp_key'])
            server.sendmail(user, user_list, message.as_string())
            INFO.logger.info("send email success !")
        except Exception as e:
            ERROR.logger.error(f"send email failed : {e}")
        finally:
            server.close()


if __name__ == '__main__':
    aa = SendEmail()
    aa.send_email("======================\n这是一个测试邮箱：\n  不用回复！\n ======================")
